<?php
	include_once('classes/view.php');
	
	View::displayHeader();
	
	if ($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != ''){
		include_once('classes/functionDb.php');
		
		try {
			$MyConn   = ConnectUser();
			$MyQuery  = "SELECT 1 FROM equipment WHERE user_id=" . $_SESSION['user_id'];
			$MyResult = $MyConn -> query($MyQuery);
		
			mysqli_close($MyConn);
			if (!$MyResult) Throw New Exception("Błąd podczas pobierania informacji z bazy danych");
			
			$MyNewQuery = "";

			if ($MyResult -> num_rows > 0){
				$MyNewQuery = "	UPDATE equipment SET 	MOTHERBOARD_ID=" . (($_POST['motherboard'] == '') ? 'NULL' : $_POST['motherboard']) . ",
														PROCESSOR_ID=" . (($_POST['processor'] == '') ? 'NULL' : $_POST['processor']) . ",
														MEMORY_ID=" . (($_POST['memory'] == '') ? 'NULL' : $_POST['memory']) . ",
														GRAPHIC_ID=" . (($_POST['graphic'] == '') ? 'NULL' : $_POST['graphic']) . ",
														DISK_ID=" . (($_POST['disk'] == '') ? 'NULL' : $_POST['disk']) . "
								WHERE user_id=" . $_SESSION['user_id'];
			} else {
				$MyNewQuery = "	INSERT INTO equipment (user_id, motherboard_id, processor_id, memory_id, graphic_id, disk_id)
								VALUES
								(
									" . $_SESSION['user_id'] . ",
									" . (($_POST['motherboard'] == '') ? 'NULL' : $_POST['motherboard']) . ",
									" . (($_POST['processor'] == '') ? 'NULL' : $_POST['processor']) . ",
									" . (($_POST['memory'] == '') ? 'NULL' : $_POST['memory']) . ",
									" . (($_POST['graphic'] == '') ? 'NULL' : $_POST['graphic']) . ",
									" . (($_POST['disk'] == '') ? 'NULL' : $_POST['disk']) . "
								)";
			}
			
			$MyNewConn 		= ConnectDb();
			$MyNewResult 	= $MyNewConn -> query($MyNewQuery);

			if (!$MyNewResult) Throw New Exception("Nie powiodła się operacja aktualizacji danych o sprzęcie");
			
			View::displayMiddle("Zakutalizowano informacje o sprzęcie.");
			
		} catch (Exception $ex){
			View::displayMiddle($ex->getMessage());	
		}
	} else {
		View::displayMiddle("Nie poprawna obsługa żadania.");
	}
	View::displayFooter();
	die();
?>